package com.zlt.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(value = "/*", initParams = @WebInitParam(name = "charset", value = "utf-8"))
public class CharsetFilter implements Filter {

    private String charset;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        charset = filterConfig.getInitParameter("charset");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String method = req.getMethod();
        if ("post".equalsIgnoreCase(method)) {
            req.setCharacterEncoding(charset);
        }
        response.setContentType("application/json;charset=" + charset);
        chain.doFilter(req, response);
    }

    @Override
    public void destroy() {

    }

}
